import 'package:bitcoin_mine/services/in_app_purchase_service.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../common/global.dart';
import '../model/mine_info.dart';
import '../widgets/invitation_code_dialog.dart';

class HomeController extends GetxController {
  // 挖矿状态
  final RxString miningStatus = '24 hours 3.40 Gh/s'.obs;
  final RxString balance = '0.0000000017739520'.obs;

  // 内购相关
  final RxBool isLoadingProducts = false.obs;
  final RxString errorMessage = ''.obs;

  // 产品ID列表 - 对应不同的订阅计划
  static List<String> productIds = [];
  late InAppPurchaseService inAppPurchaseService;

  @override
  void onInit() {
    super.onInit();
    inAppPurchaseService = Get.find<InAppPurchaseService>();
    // 延迟显示邀请码对话框，确保首页已完全加载
    Future.delayed(const Duration(milliseconds: 500), () {
      _showInvitationCodeDialogIfNeeded();
    });
  }

  /// 检查是否需要显示邀请码对话框
  Future<void> _showInvitationCodeDialogIfNeeded() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final hasShownInvitationDialog =
          prefs.getBool('has_shown_invitation_dialog') ?? false;

      // 如果已经显示过对话框，则不再次显示
      if (hasShownInvitationDialog) {
        return;
      }

      // 显示邀请码对话框
      final result = await Get.dialog(
        const InvitationCodeDialog(),
        barrierDismissible: true,
      );
      await prefs.setBool('has_shown_invitation_dialog', true);
      // if (result != null && result is String) {
      //   // 保存邀请码
      //   await prefs.setString('invitation_code', result);
      //   await prefs.setBool('has_shown_invitation_dialog', true);

      //   // 更新全局邀请码（用于注册时使用）
      //   Global.platformRefer = result;

      //   print('邀请码已保存: $result');
      // }
    } catch (e) {
      print('显示邀请码对话框失败: $e');
    }
  }

  // 订阅层级选择
  final RxInt selectedTier =
      0.obs; // 0: BASIC, 1: MODERATE, 2: ADVANCED, 3: TOP-TIER

  // 订阅计划选择
  final RxInt selectedPlan = 0.obs; // 0: 第一个计划, 1: 第二个计划, 2: 第三个计划

  // 订阅层级列表
  final List<String> subscriptionTiers = [
    'BASIC',
    'MODERATE',
    'ADVANCED',
    'TOP-TIER',
  ];

  // 本地虚构订阅计划数据已移除，改为直接使用 mine_info 中的真实商品数据

  // 选择订阅层级
  void selectTier(int index) {
    selectedTier.value = index;
    // 重置选择的计划为第一个
    selectedPlan.value = 0;
  }

  // 选择订阅计划
  void selectPlan(int index) {
    selectedPlan.value = index;
  }

  /// 根据层级和计划获取对应的产品ID
  String _getProductId(int tier, int plan) {
    final tierNames = ['basic', 'moderate', 'advanced', 'top'];
    final planNames = ['month', 'season', 'year'];

    if (tier >= tierNames.length || plan >= planNames.length) {
      return '';
    }
    print('${tierNames[tier]}_${planNames[plan]}');
    return '${tierNames[tier]}_${planNames[plan]}';
  }

  /// 获取当前选择的产品
  ProductDetails? getCurrentProduct() {
    return inAppPurchaseService.getCurrentProduct(
      selectedTier.value,
      selectedPlan.value,
    );
  }

  /// 获取产品价格显示文本
  String getProductPriceText(int tier, int plan) {
    final productId = _getProductId(tier, plan);
    if (productId.isEmpty) return '价格加载中...';

    try {
      final product = inAppPurchaseService.availableProducts.firstWhere(
        (p) => p.id == productId,
      );
      return product.price;
    } catch (e) {
      return '价格加载中...';
    }
  }

  /// 检查产品是否可用
  bool isProductAvailable(int tier, int plan) {
    final productId = _getProductId(tier, plan);
    if (productId.isEmpty) return false;

    return inAppPurchaseService.availableProducts.any(
      (product) => product.id == productId,
    );
  }

  // 更新挖矿状态
  void updateMiningStatus(String status) {
    miningStatus.value = status;
  }

  // 更新余额
  void updateBalance(String newBalance) {
    balance.value = newBalance;
  }

  // 从 mine_info 中获取当前选中的 Good
  Good? get _currentGood {
    final MineInfo? info = Global.mineInfo.value;
    if (info == null) return null;
    final List<Good> goods = _goodsByTier(info, selectedTier.value);
    if (goods.isEmpty || selectedPlan.value >= goods.length) return null;
    return goods[selectedPlan.value];
  }

  // 获取当前选择的价格
  String get currentSelectedPrice {
    final Good? g = _currentGood;
    if (g == null) return '\$0.00/1 month';
    return '\$${g.price.toStringAsFixed(2)}/${periodText(g.circle)}';
  }

  // 获取当前选择的详情
  String get currentSelectedDetails {
    // 目前 UI 固定描述
    return '+ Continuous improvement\nMining speed';
  }

  // 获取当前选择的挖矿速度
  String get currentSelectedSpeed {
    final Good? g = _currentGood;
    if (g == null) return '0 Gh/s';
    return '${g.hashrate.toStringAsFixed(2)} Gh/s';
  }

  List<Good> _goodsByTier(MineInfo info, int tier) {
    switch (tier) {
      case 0:
        return info.goods_map.group1;
      case 1:
        return info.goods_map.group2;
      case 2:
        return info.goods_map.group3;
      case 3:
        return info.goods_map.group4;
      default:
        return info.goods_map.group1;
    }
  }

  String periodText(int circle) {
    switch (circle) {
      case 1:
        return 'week';
      case 2:
        return 'month';
      case 3:
        return 'season';
      case 4:
        return 'year';
      default:
        return 'month';
    }
  }
}
